package com.suneast.suneaststore.modules.personal.wallet.bankcard;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.bean.personal.bank.BankCardBean;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.wallet.WalletHandler;
import com.suneast.suneaststore.modules.personal.wallet.bankcard.adapter.BankCardListAdapter;
import com.suneast.suneaststore.modules.personal.wallet.bankcard.event.AddBankCardResult;
import com.suneast.suneaststore.modules.personal.wallet.bankcard.event.DeleteBankCardResult;
import com.suneast.suneaststore.modules.personal.wallet.bankcard.event.GotBankCardList;
import com.suneast.suneaststore.ui.dialog.CancelConfirmDialog;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.suneast.suneaststore.ui.recycler.decoration.SpaceItemDecoration;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

public class BankCardListFragment extends BaseFragment implements CancelConfirmDialog.ConfirmBtnClickListener {
    @Override
    public int setLayout() {
        return R.layout.fragment_bank_card_list;
    }

    public static final int TypeChoose = 1;
    public static final int SucessCode = 1;

    private int type = -1;

    public BankCardListFragment withType(int type) {
        this.type = type;
        return this;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initView();
        WalletHandler.requestBackCardList();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @OnClick({R.id.layout_add_card})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.layout_add_card: {
                start(new AddBankCardFragment());
            }
            break;
        }
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv_bank_card)
    SwipeMenuRecyclerView bankCardRV;
    BankCardListAdapter adapter;

    CancelConfirmDialog dialog = null;

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> pop());
        dialog = new CancelConfirmDialog();
        Bundle bundle = new Bundle();
        bundle.putString("content", _mActivity.getString(R.string.delete_address_tip));
        dialog.setArguments(bundle);
        dialog.setListener(this);

        bankCardRV.setLayoutManager(new LinearLayoutManager(getContext()));
        bankCardRV.addItemDecoration(new SpaceItemDecoration(0, 0, 10, 10));
        int height = getResources().getDimensionPixelSize(R.dimen.swipe_delete_btn_height_dp);
        int width = getResources().getDimensionPixelSize(R.dimen.swipe_delete_btn_width_dp);
        // 创建菜单：
        SwipeMenuCreator mSwipeMenuCreator =
                (SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) -> {
                    SwipeMenuItem deleteItem = new SwipeMenuItem(getContext())
                            .setText("删除")// 各种文字和图标属性设置。
                            .setTextColor(Color.WHITE)
                            .setHeight(height)
                            .setWidth(width)
                            .setBackgroundColor(getResources().getColor(R.color.orange));
                    rightMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。

                };

        // 设置监听器。
        bankCardRV.setSwipeMenuCreator(mSwipeMenuCreator);

        SwipeMenuItemClickListener mMenuItemClickListener = (SwipeMenuBridge menuBridge) -> {
            // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
            menuBridge.closeMenu();
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            confirmPos = adapterPosition;
            dialog.show(getFragmentManager(), "");

        };

        // 菜单点击监听。
        bankCardRV.setSwipeMenuItemClickListener(mMenuItemClickListener);

        adapter = new BankCardListAdapter(R.layout.item_bank_card);
        bankCardRV.setAdapter(adapter);
        if (type == TypeChoose) {
            adapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
                BankCardBean bean = (BankCardBean) adapter.getData().get(position);
                Bundle cardBundle = new Bundle();
                cardBundle.putInt("card_id", bean.getId());
                cardBundle.putString("bank_name", bean.getBankName());
                cardBundle.putString("card_num", bean.getNum());
                setFragmentResult(SucessCode, cardBundle);
                pop();
            });
        }
    }

    private void deleteBankCard(int id) {
        Log.e(TAG, "deleteBankCard: ");
        RestClient.builder()
                .url(API.DELETE_BANK_CARD)
                .params("token", AccountManager.getToken())
                .params("id", id)
                .success(response -> {
                    JSONObject rootObj = JSONObject.parseObject(response);
                    LatteLogger.json("test", response);
                    if (rootObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new DeleteBankCardResult(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new DeleteBankCardResult(Flag.Result.FAILURE));
                    }
                })
                .failure(() -> {
                    EventBus.getDefault().post(new DeleteBankCardResult(Flag.Result.FAILURE));
                    LatteLogger.e("test", "deleteBankCard failure ");
                })
                .error((code, msg) -> {
                    EventBus.getDefault().post(new DeleteBankCardResult(Flag.Result.FAILURE));
                    LatteLogger.e("test", "deleteBankCard error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteBankCard(DeleteBankCardResult result) {
        if (result.getFlag() == Flag.Result.SUCCEED) {
            adapter.remove(confirmPos);
        } else {
            confirmPos = -1;
            Toast.makeText(_mActivity, "删除银行卡失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotBankCardList(GotBankCardList event) {
        Log.e(TAG, "onGotBankCardList: size = " + event.getBankCardList().size());
        adapter.setNewData(event.getBankCardList());
    }

    private int confirmPos = -1;

    @Override
    public void onConfirm() {
        if (confirmPos != -1) {
            BankCardBean bean = adapter.getData().get(confirmPos);
            deleteBankCard(bean.getId());
        }
        dialog.dismiss();
    }

    @Override
    public void onCancel() {
        dialog.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddResult(AddBankCardResult result) {
        if (result.getResult() == Flag.Result.SUCCEED) {
            WalletHandler.requestBackCardList();
        }
    }
}
